<?php

	/**
	* TABLEPREFIX: is configured in the include/config.php file included by the general_include.php
	*/
	include("general_include.php");
	include_once("adodb/dbconfig.php");
	
	include "checklogin.php";

	function getPostOrGetParam($param){
		if(isset($_POST[$param]))
			return $_POST[$param];
		else{
			if(isset($_GET[$param]))
				return $_GET[$param];
			else
				return "";
		}
	}
	
	function markReadMessages($messageIds, $fromUserId=null) {
		// Accesing the global object inside the local scope
		global $UserManagerObjAjax;
		
		if (isset($messageIds) && is_array($messageIds))
			$messageIds = implode(",",$messageIds);
		
		$sqlQuery = "UPDATE ". TABLEPREFIX ."_message SET is_read='Y' ";
		
		if (isset($messageIds))
			$sqlQuery .= "WHERE message_id in (". $messageIds .")";
		elseif (isset($fromUserId))
			$sqlQuery .= "WHERE  user_id_from=". $fromUserId ." AND reply_of_msg=-1";
		
		if (isset($messageIds) || isset($fromUserId))
			$UserManagerObjAjax->Execute($sqlQuery);
		
	}
	
	function messagesPending() {
		// Accesing the global object inside the local scope
		global $UserManagerObjAjax;
		
		$userId = $_SESSION['user_id'];
		
		$sqlQuery = "SELECT u.user_id, u.name, m.message_id, m.message_text, ups.phono_session_id "
					."FROM ". TABLEPREFIX ."_message m, ". TABLEPREFIX ."_user u, ". TABLEPREFIX ."_user_phono_session ups "
					."WHERE m.user_id_from=u.user_id AND ups.nk_user_id=u.user_id AND user_id_to=". $userId ." AND is_read='N' AND reply_of_msg=-1";
					
		$messages = $UserManagerObjAjax->GetRecords("All",$sqlQuery);

		$ret = array();
		$messagesIdToUpdate = array();
		for($i=0;$i<count($messages);$i++) {
			$theFromChatSession = &$ret[$messages[$i]['user_id']];
			
			if (!isset($theFromChatSession)) {
				$theFromChatSession = array(
					"fromUserId"	=> $messages[$i]['user_id'],
					"fromName"		=> $messages[$i]['name'],
					"sessionId"		=> $messages[$i]['phono_session_id'],
					"messages"		=> array(),
				);
				$ret[$messages[$i]['user_id']] = &$theFromChatSession;
			}
			
			$theFromChatSession['messages'][]=$messages[$i]['message_text'];
			$messagesIdToUpdate[]=$messages[$i]['message_id'];
		}
		
		markReadMessages($messagesIdToUpdate);
		
		return $ret;
	}
	
	function friendList() {
		// Accesing the global object inside the local scope
		global $UserManagerObjAjax;
		
		$userId = $_SESSION['user_id'];
		
		$sqlQuery = "SELECT u.user_id userId, u.name userName, ufl.friend_status status, ups.status connectionStatus "
					."FROM ". TABLEPREFIX ."_user_phono_session ups, ". TABLEPREFIX ."_user u, ". TABLEPREFIX ."_user_friends_list ufl "
					."WHERE ufl.nk_user_id_friend=u.user_id AND ups.nk_user_id=u.user_id AND ufl.nk_user_id_owner=". $userId;
		
		$friendsList = $UserManagerObjAjax->GetRecords("All",$sqlQuery);
		
		$ret=array();
		for($i=0;$i<count($friendsList);$i++) {
			$ret[$friendsList[$i]["userId"]]=array(
				"userId"			=>$friendsList[$i]["userId"],
				"userName"			=>$friendsList[$i]["userName"],
				"status"			=>$friendsList[$i]["status"],
				"connectionStatus"	=>$friendsList[$i]["connectionStatus"],
			);
		}
		
		return $ret;
	}
	
	function connect($sId) {
		// Accesing the global object inside the local scope
		global $UserManagerObjAjax;
		
		$userId = $_SESSION['user_id'];
		
		$db = new DBConnection();
		$db->getConnection();
		
		$sqlQuery = "SELECT * FROM  ". TABLEPREFIX ."_user_phono_session WHERE nk_user_id=". $userId;
		$handle = mysql_query($sqlQuery);
		$record = mysql_fetch_row($handle);
		if ($record=="") {
			$sqlQuery = "INSERT ". TABLEPREFIX ."_user_phono_session(nk_user_id, phono_session_id, status) values (". $userId .", '". $sId ."', 1)"; 
		} else {
			$sqlQuery = "UPDATE ". TABLEPREFIX ."_user_phono_session SET  phono_session_id='". $sId ."', status=1 WHERE nk_user_id=". $userId; 
		}
		
		mysql_query($sqlQuery);
		
		$sqlQuery = "SELECT ups.phono_session_id sessionId, u.name FROM  ". TABLEPREFIX ."_user_phono_session ups, ". TABLEPREFIX ."_user u "
					."WHERE u.user_id = ups.nk_user_id AND ups.nk_user_id=". $userId;
		$handle = mysql_query($sqlQuery);
		$record = mysql_fetch_object($handle);
		
		$ret['myInfo'] = array(
			"myUserId"			=> $userId,
			"myName"			=> $record->name,
			"mySessionId"		=> $record->sessionId,
			"friendsList"		=> friendList(),
			"messagesPending"	=> messagesPending(),
		);
		return $ret;
	}
	
	function toSessionInfo($toUserId) {
		// Accesing the global object inside the local scope
		global $UserManagerObjAjax;
		
		$db = new DBConnection();
		$db->getConnection();
		
		
		$sqlQuery = "SELECT ups.phono_session_id sessionId, u.name FROM  ". TABLEPREFIX ."_user_phono_session ups, ". TABLEPREFIX ."_user u "
					."WHERE u.user_id = ups.nk_user_id AND ups.nk_user_id=". $toUserId;
					
		logToFile("SQLITO: ". $sqlQuery);
		$handle = mysql_query($sqlQuery);
		if (mysql_num_rows($handle) > 0) {
			$record = mysql_fetch_object($handle);
			$sessionId = $record->sessionId;
			$toName = $record->name;
		}
		
		$ret['chatSession'] = array(
			'sessionId' =>	$sessionId,
			'toName'	=>	$toName,
			'toUserId'	=>	$toUserId,
		);
	
		return $ret;
	}
	
	function registerMessageTo($chatSession, $msgText) {
		// Accesing the global object inside the local scope
		global $UserManagerObjAjax;
	
		$userId = $_SESSION['user_id'];
	
		//$db = new DBConnection();
		//$db->getConnection();
		
		$table_name = TABLEPREFIX."_message ";
		
		$dateAdded	= date('Y-m-d H:i:s');
		$fields_values = array( 
			'user_id_to'  			=> $chatSession['toUserId'],
			'user_id_from'  		=> $userId,										
			'reply_of_msg'  		=> "-1", // THE -1 will indicate the chat type messages.
			'message_text'  		=> "'$msgText'",
			'date_added'  			=> "'$dateAdded'"
		);
		
		$values=array();
		$keys=array();
		foreach($fields_values as $key=>$value) {
			$keys[]=$key;
			$values[]=$value;
		}
		$sqlQuery = "INSERT INTO ". TABLEPREFIX ."_message(". implode(",", $keys) .") VALUES (". implode(",", $values) .")";
		$msgreport	= $UserManagerObjAjax->Execute($sqlQuery);
		
		$message_id=mysql_insert_id();
		
		return $message_id;
	
	}
	
	$method = getPostOrGetParam("method");
	if($method != ""){
		header('Content-type:text/javascript;charset=UTF-8');

		switch ($method) {
			case "connect":
				$sId = getPostOrGetParam("sId");
				$ret = connect($sId);
				break;
			case "refreshSession":
				break;
			case "chatSessionInfo":
				$toUserId = getPostOrGetParam("uId");
				$ret = toSessionInfo($toUserId);
				break;
			case "outbound":
				$chatSession = getPostOrGetParam("toChatSession");
				
				$msgText = getPostOrGetParam("message");
				$ret = isset($chatSession['toUserId']) ? toSessionInfo($chatSession['toUserId']) : toSessionInfo($chatSession['fromUserId']);
				$ret['messageIdGen'] = registerMessageTo($chatSession, $msgText);
				break;
			case "inbound":
				$fromUserId = getPostOrGetParam("fromUserId");
				$messageToMark = getPostOrGetParam("messageIdGen");
				markReadMessages($messageToMark, $fromUserId);
				break;
		}
	}
	
	echo json_encode($ret);
?>